package db

import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"log"
)

type Pg struct {
	db *gorm.DB
}

var G_pg Pg

func (ddb *Pg) DbClose() {

}
func (ddb *Pg) InitDbPg() {
	dsn := "host=" + PQ_HOST + " user=postgres password=postgres dbname=iot_platform port=" + PQ_PORT + " sslmode=disable TimeZone=Asia/Shanghai"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalln("[DB ERROR]:", err)
	}
	err = db.AutoMigrate(&DeviceBasics{}, &GridPower{}, &BmsPower{})
	if err != nil {
		log.Fatalln("[DB ERROR]:", err)
	}
	ddb.db = db
}

func (db *Pg) InsertPg(data interface{}) {
	if db.db == nil {
		return
	}
	db.db.Create(data)
}

func (db *Pg) WhereFind(sql string, data interface{}) {
	//db.db.Where("created_at > '2024-08-29 13:00:00' AND created_at < '2024-08-29 14:00:00'").Find(&basics)
	if db.db == nil {
		return
	}
	tx := db.db.Where(sql).Find(data)
	if tx.Error != nil {
		log.Fatalln("[DB ERROR]:", tx.Error)
	}
}
